# 
#    Author : Inigo Gonzalez Vazquez <ingonza85 __at__ gmail __dot__ com>
#


from xml.dom import minidom
from xml.dom.minidom import Document
import copy
import urllib
from models import Person
import os
from os import path

from social.privacy.exceptions import PermissionError 

def getChildrenByVar(node, name):
    for child in node.childNodes:
        if child.nodeType==child.ELEMENT_NODE and (name=='*' or child.tagName==name):
            yield child

def get_data(url, viewer):
    """
    Returns the details for a question
    """
    try:
        #using the user id it gets his email address and sends a request for that email
        p = Person.objects.get(pk=viewer)
        email = p.email
        question = {}
        url = url + email + "/es/"
        file = urllib.urlopen(url)
    except:
        return "free"
    try:  
        #here the servers answer is parsed to get the question and to send it to th client  
        dom = minidom.parse(file) 
        temp = dom.getElementsByTagName('response')
        resp = 'free'
        for node in temp:
            resp = node.getAttribute('status')
        if resp == "error":
            return resp
        if resp == 'free':
            return resp      
        temp = dom.getElementsByTagName('question')
        for node in temp:
            alist = list(getChildrenByVar(node,'identifier'))[0]
            question['id'] = copy.deepcopy(alist.firstChild.data)
            alist = list(getChildrenByVar(node,'topic'))[0]
            question['topic'] = copy.deepcopy(alist.firstChild.data)
            alist = list(getChildrenByVar(node,'text'))[0]
            question['text'] = copy.deepcopy(alist.firstChild.data)
            alist = list(getChildrenByVar(node,'type'))[0]
            question['type'] = copy.deepcopy(alist.firstChild.data)      
            a = {}
            answers = []
            n = 0
            temp = dom.getElementsByTagName('answer')
            for node in temp:
                alist = list(getChildrenByVar(node,'code'))[0]
                a['code'] = alist.firstChild.data
                alist = list(getChildrenByVar(node,'text'))[0]
                a['text'] = alist.firstChild.data
                answers += [a]
                answers[n] = copy.deepcopy(a)
                n = n +1
        question['answer'] = answers
    except:
        return "xml"    
    try:    
        #Thinking about improving the server to change an answer that has been given we save the question to reduce the traffic between servers
        path2 = path.dirname(path.abspath(__file__)) + "/questions/received/%s.xml" % (str(question['id']))
        if os.path.isfile(path2):
            os.remove(path2)
        questionFile = open(path2,'w')
        s = dom.toxml()
        s = s.encode('UTF-8')
        questionFile.write(str(s))
        questionFile.close()
        return question
    except:
        return "file"
    
#this function makes the same thing as the previus one but it doesn't get the mail from id, it must receive it. It is used for testing  
def get_bymail(url, email):
    """
    Returns the details for a question
    """
    try:
        question = {}
        url = url + email + "/es/"
        file = urllib.urlopen(url)
    except:
        return "free"
    try:    
        dom = minidom.parse(file) 
        temp = dom.getElementsByTagName('response')
        resp = 'free'
        for node in temp:
            resp = node.getAttribute('status')
        if resp == "error":
            return resp
        if resp == 'free':
            return resp      
        temp = dom.getElementsByTagName('question')
        for node in temp:
            alist = list(getChildrenByVar(node,'identifier'))[0]
            question['id'] = copy.deepcopy(alist.firstChild.data)
            alist = list(getChildrenByVar(node,'topic'))[0]
            question['topic'] = copy.deepcopy(alist.firstChild.data)
            alist = list(getChildrenByVar(node,'text'))[0]
            question['text'] = copy.deepcopy(alist.firstChild.data)
            alist = list(getChildrenByVar(node,'type'))[0]
            question['type'] = copy.deepcopy(alist.firstChild.data)      
            a = {}
            answers = []
            n = 0
            temp = dom.getElementsByTagName('answer')
            for node in temp:
                alist = list(getChildrenByVar(node,'code'))[0]
                a['code'] = alist.firstChild.data
                alist = list(getChildrenByVar(node,'text'))[0]
                a['text'] = alist.firstChild.data
                answers += [a]
                answers[n] = copy.deepcopy(a)
                n = n +1
        question['answer'] = answers
    except:
        return "xml"    
    try:    
        path2 = path.dirname(path.abspath(__file__)) + "/questions/received/%s.xml" % (str(question['id']))
        if os.path.isfile(path2):
            os.remove(path2)
        questionFile = open(path2,'w')
        s = dom.toxml()
        s = s.encode('UTF-8')
        questionFile.write(str(s))
        questionFile.close()
        return question
    except:
        return "file"
    

###################################################################This is the code for seding the answers#################3

def send_data (url, data):
    try:
        #Gets all the user data using its id and sends the data to the server
        p = Person.objects.get(pk=data['user'])
        params = {'question_id' : data['id'], 'person_email' : p.email , 'language' : data['language'], 'answers' : data['answers'], 'comment' : data['comment']}
        file = urllib.urlopen(url, urllib.urlencode(params)) #file will store the server's answer
        path2 = path.dirname(path.abspath(__file__)) + "/questions/answered/%s.xml" % (p.email)
        #If the file doesn't exist it creates the dom tree to save on it , this is made thinking on improving this module and reducing the traffic
        if not os.path.isfile(path2):
            doc = Document()
            questionList = doc.createElement("questions")
            doc.appendChild(questionList)
            questionTag = doc.createElement("question")
            questionList.appendChild(questionTag)
            idTag = doc.createElement("id")
            questionTag.appendChild(idTag)
            idText = doc.createTextNode(str(data['id']))
            idTag.appendChild(idText)
        #If the file exists it reads it to generate the dom tree to save on it and removes the file, this is made thinking on improving this module and reducing the traffic          
        else:    
            doc = minidom.parse(path2)
            questionList = doc.getElementsByTagName("questions")
            questionTag = doc.createElement("question")
            questionList[0].appendChild(questionTag)
            idTag = doc.createElement("id")
            questionTag.appendChild(idTag)
            idText = doc.createTextNode(str(data['id']))
            idTag.appendChild(idText)
            os.remove(path2)
    except:
        return "free"
    try:        
        #generates the file and stores in it the DOM tree
        xmlfile = open (path2, 'w')
        s = doc.toxml()
        s = s.encode('UTF-8')
        xmlfile.write(str(s))
        xmlfile.close()
    except:
        return "file";    
    
    try:    
        dom = minidom.parse(file) 
        temp = dom.getElementsByTagName('response')
        resp = 'free'
        for node in temp:
            resp = node.getAttribute('status')
        return resp 
    except:
        return "xml"
    
    
#this function makes the same thing as the previus one but it doesn't get the mail from id, it must receive it. It is used for testing     
def send_bymail (url, data, email):
    try:
        params = {'question_id' : data['id'], 'person_email' : email , 'language' : data['language'], 'answers' : data['answers'], 'comment' : data['comment']}
        file = urllib.urlopen(url, urllib.urlencode(params)) #file will store the server's answer
        path2 = path.dirname(path.abspath(__file__)) + "/questions/answered/%s.xml" % (email)
    except:
        return "free"    
    if not os.path.isfile(path2):
        doc = Document()
        questionList = doc.createElement("questions")
        doc.appendChild(questionList)
        questionTag = doc.createElement("question")
        questionList.appendChild(questionTag)
        idTag = doc.createElement("id")
        questionTag.appendChild(idTag)
        idText = doc.createTextNode(str(data['id']))
        idTag.appendChild(idText)      
    else:    
        doc = minidom.parse(path2)
        questionList = doc.getElementsByTagName("questions")
        questionTag = doc.createElement("question")
        questionList[0].appendChild(questionTag)
        idTag = doc.createElement("id")
        questionTag.appendChild(idTag)
        idText = doc.createTextNode(str(data['id']))
        idTag.appendChild(idText)
        os.remove(path2)
    xmlfile = open (path2, 'w')
    s = doc.toxml()
    s = s.encode('UTF-8')
    xmlfile.write(str(s))
    xmlfile.close()
    try:    
        dom = minidom.parse(file) 
        temp = dom.getElementsByTagName('response')
        resp = 'free'
        for node in temp:
            resp = node.getAttribute('status')
        return resp 
    except:
        return "xml"    
    
